package com.bowen.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bowen.gulimall.product.service.CategoryBrandRelationService;
import com.bowen.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bowen.common.utils.PageUtils;
import com.bowen.common.utils.Query;

import com.bowen.gulimall.product.dao.CategoryDao;
import com.bowen.gulimall.product.entity.CategoryEntity;
import com.bowen.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有的
        List<CategoryEntity> entityList = baseMapper.selectList(null);

        List<CategoryEntity> treeList = entityList.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildren(menu, entityList));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return treeList;
    }

    @Override
    public void removeMenus(List<Long> asList) {
        // TODO: 2022/11/1 涉及其他业务不能删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long attrGroupId) {
        List<Long> path = new ArrayList<>();
        List<Long> catelogPath = getCatelogPath(attrGroupId, path);
        Collections.reverse(catelogPath);
        return catelogPath.toArray(new Long[catelogPath.size()]);
    }

    /**
     * 级联更新所以关联的数据
     *
     * @param category
     */
    //注意一定要加上单引号
//    @Caching(evict = {
//            @CacheEvict(value = "category",key = "'selectLevel1List'"),
//            @CacheEvict(value = "category",key = "'getCatalogJson'")
//    })
    @CacheEvict(value = "category", allEntries = true)
    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> selectLevel1List() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        return categoryEntityList;
    }

    /**
     * 使用cache将数据放入缓存
     *
     * @return
     */
    @Cacheable(value = {"category"}, key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        //优化查出全部的数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有1级分类
        List<CategoryEntity> level1List = selectLevel1List();
        System.out.println("查询了数据库.....");
        //封装数据
        Map<String, List<Catelog2Vo>> listMap = level1List.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> leveLog2List = getParent_cid(selectList, v.getCatId());
            //封装上面的结果
            List<Catelog2Vo> collect = null;
            if (leveLog2List != null) {
                collect = leveLog2List.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前二级分类的三级分类封装成vo

                    List<CategoryEntity> leve3List = getParent_cid(selectList, l2.getCatId());
                    if (leve3List != null) {
                        List<Catelog2Vo.Catelog3Vo> catelog3VoList = leve3List.stream().map(l3 -> {
                            //封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3VoList);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        return listMap;
    }

    public Map<String, List<Catelog2Vo>> getgetCatalogJson2() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            System.out.println("缓存不命中....查询数据库...");
            Map<String, List<Catelog2Vo>> catalogJsonFormDb = getCatalogJsonFormDbWithRedisLock();
            return catalogJsonFormDb;
        }
        System.out.println("缓存命中.....直接返回...");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }


    private Map<String, List<Catelog2Vo>> getDataFormDb() {
        //加锁
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            //缓存中有就直接进行返回了
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }

        //优化查出全部的数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有1级分类
        List<CategoryEntity> level1List = selectLevel1List();
        System.out.println("查询了数据库.....");
        //封装数据
        Map<String, List<Catelog2Vo>> listMap = level1List.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> leveLog2List = getParent_cid(selectList, v.getCatId());
            //封装上面的结果
            List<Catelog2Vo> collect = null;
            if (leveLog2List != null) {
                collect = leveLog2List.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前二级分类的三级分类封装成vo

                    List<CategoryEntity> leve3List = getParent_cid(selectList, l2.getCatId());
                    if (leve3List != null) {
                        List<Catelog2Vo.Catelog3Vo> catelog3VoList = leve3List.stream().map(l3 -> {
                            //封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3VoList);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));

        //将查询的结果放入缓存
        String s = JSON.toJSONString(listMap);
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);//这里可以加入时间

        return listMap;
    }

    /**
     * 使用redisson分布式锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFormDbWithRedissonLock() {
        RLock lock = redissonClient.getLock("CatalogJson-lock");
        lock.lock();
        //在加锁的同时设置失效时间以保证不会发生死锁的状况
        Map<String, List<Catelog2Vo>> dataFormDb = null;
        try {
            dataFormDb = getDataFormDb();
        } finally {
            lock.unlock();
        }
        return dataFormDb;
    }

    /**
     * 分布式锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFormDbWithRedisLock() {
        //生成唯一标识
        String uuid = UUID.randomUUID().toString();
        //在加锁的同时设置失效时间以保证不会发生死锁的状况
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            Map<String, List<Catelog2Vo>> dataFormDb = null;
            try {
                dataFormDb = getDataFormDb();
            } finally {
                //使用lua脚本进行解锁，用try catch来延长锁的时效
                //因为脚本的执行就只要两种结果要么成功要么失败，利用唯一标识来删除锁，这样不会发生误删他人锁的事情发生
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"), uuid);
            }
            return dataFormDb;
        } else {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return getCatalogJsonFormDbWithRedisLock();//自旋的方式
        }


    }

    /**
     * 本地锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFormDbWithLocalLock() {
        //加锁

        //本地锁synchronized，juc(lock)都是进程锁，在分布式情况下，想要锁住所有，就必须使用分布式锁

        synchronized (this) {
            return getDataFormDb();
        }


    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long partntsCid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == partntsCid).collect(Collectors.toList());
        return collect;
    }

    public List<Long> getCatelogPath(Long id, List<Long> path) {
        path.add(id);
        CategoryEntity categoryEntity = baseMapper.selectById(id);
        if (categoryEntity.getParentCid() != 0) {
            getCatelogPath(categoryEntity.getParentCid(), path);
        }
        return path;
    }

    public List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }


}